# -*- coding: utf-8 -*-
'''
@author: olivia.dou
Created on: 3/19/2021 11:03
desc: 标准化配置相关代码
'''
import logging
import traceback

from util.db_util import execute_query


def get_std_mapping_fin_item_id(disclosed_name, std_code, biz_code):
    """获取指定披露名称、业务的科目容错id

    :param disclosed_name: 披露名称
    :param biz_code: 业务code

    :return: 科目容错名称、业务的id
    """
    results = execute_query("SELECT id FROM `t_das_std_mapping_fin_item` WHERE `disclosed_name`='%s'AND std_code='%s' AND biz_code='%s'"
                            % (disclosed_name, std_code, biz_code))
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None


def get_biz_element_mapping_id(model_name, biz_code, client_code):
    """获取指定业务元素映射id

    :param model_name: 模型名称
    :param biz_code: 业务code
    :param client_code: 业务分组code

    :return: 业务元素映射id
    """
    results = execute_query(
        "SELECT sbe.id FROM t_das_std_biz_element AS sbe JOIN t_das_model AS model ON sbe.model_id=model.id  WHERE model.model_name='%s' AND sbe.biz_code='%s' AND sbe.client_code='%s'" % (
            model_name, biz_code, client_code))
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None


def get_std_mapping_col_id(disclosed_name, tbl_name, stdcol_name, biz_code=None):
    """获取指定披露名称、标准化数据列名、业务code的数据列容错id

    :param disclosed_name: 披露名称
    :param stdcol_name: 标准化字段名
    :param biz_code: 业务code

    :return: 对应的标准化数据列id
    """
    results = execute_query(
        "SELECT id FROM t_das_std_mapping_tbl WHERE disclosed_name = '%s' AND std_col_name = '%s' AND biz_code = '%s' AND tbl_name='%s'" % (
            disclosed_name, stdcol_name, biz_code, tbl_name)) if biz_code else execute_query(
        "SELECT id FROM t_das_std_mapping_tbl WHERE disclosed_name = '%s' AND std_col_name = '%s' AND tbl_name='%s'" % (
            disclosed_name, stdcol_name, tbl_name))
    try:
        result = results[0][0]
        return result
    except Exception as e:
        logging.error("no result retrieved")
        return None


def get_element_mapped_biz_codes(element_id, **kwargs):
    """获取元素映射的客户编码+业务编码

    :param element_id: 元素名称

    :return: 元素映射的(客户编码,业务编码)元组的列表
    """
    try:
        if 'order' in kwargs:
            substr = " order by %s"%kwargs['order']
        else:
            substr = ""
        sql = """select client_code, biz_code from t_das_std_biz_element where element_id=%s %s"""%(element_id,substr)
        res = execute_query(sql)
        return res
    except Exception as e:
        logging.error("get_element_mapped_biz_codes: %s"%e)
        return []


def get_element_one_mapped_biz_code(element_id, **kwargs):
    """获取和元素映射的一个业务的编码

    :param element_id: 元素id
    :param kwargs:

    :return: 和元素映射的一个业务的编码
    """
    biz_codes = get_element_mapped_biz_codes(element_id, **kwargs)
    return biz_codes[0]


def get_restate_rule_id(rule_name):
    """根据指定的重述规则定义名称获取规则ID

    :param rule_name: 述规则定义名称

    :return: 指定的重述规则ID
    """

    sql = "select id from t_das_restate_rule_def where rule_name ='%s'" % rule_name
    try:
        res = execute_query(sql)
        if res!=[]:
            return res[0][0]
        else:
            return 100
    except Exception as e:
        logging.error("get_restate_rule_id:%s" % e)


def get_restate_rule_count(**kwargs):
    """根据指定的重述规则分类方法获取符合条件的规则的数量

    :param : restateRuleType 类型
    :param : bizCode 编码

    :return: 指定的规则ID
    """

    condition = ''
    if "restateRuleType" in kwargs:
        restate_rule_type = kwargs["restateRuleType"]
        condition += "where restate_rule_type = %s"%restate_rule_type
    if "bizCode" in kwargs:
        biz_code = kwargs["bizCode"]
        condition += " and biz_code = '%s'" %biz_code
    if kwargs == []:
        condition = ''
    if condition.startswith(" and"):
        condition=condition.replace("and","where",1)
    sql = "select count(*) from t_das_restate_rule_def  " + condition
    try:
        res = execute_query(sql)[0][0]
        return res
    except Exception as e:
        logging.error("get_restate_rule_count：%s"%e)
        traceback.print_exc()
        return 0


def get_restate_rule_detail_id(rule_id, source_biz_code, source_item_code):
    """查询数据库获取重述规则明细ID

    :param :rule_id 重述规则ID
    :param :source_biz_code 源业务code
    :param :source_item_code 源科目code

    :return: 返回最新的重述规则明细ID
    """

    sql = "select id from t_das_restate_rule_def_detail  where rule_id = '%s' and source_biz_code = '%s' and source_item_code = '%s'" % (rule_id, source_biz_code, source_item_code)
    try:
        res = execute_query(sql)[0][0]
        return res
    except Exception as e:
        logging.error("get_restate_rule_detail_id:%s" % e)
        traceback.print_exc()
        return None


def get_std_rule_ids(**kwargs):
    """根据标准化规则定义条件获取规则ids

       :param kwargs:
        | rule_name: 标准化规则名称
        | target_biz_code: 标准化规则目标业务code
        | target_item_code: 标准化规则目标科目code
        | start_fy: 标准化规则开始财年
        | end_fy: 标准化规则结束财年

    :return: 指定的标准化规则ids
    """
    condition = ''
    if "target_item_code" in kwargs and "start_fy" in kwargs and "end_fy" in kwargs:
        target_item_code = kwargs["target_item_code"]
        start_fy = kwargs["start_fy"]
        end_fy = kwargs["end_fy"]
        condition += "where target_item_code = '%s' and start_fy=%s and end_fy=%s" % (target_item_code, start_fy, end_fy)
    elif "rule_name" in kwargs:
        rule_name = kwargs["rule_name"]
        condition += "where rule_name = '%s'" % rule_name
    elif "target_biz_code" in kwargs:
        target_biz_code = kwargs["target_biz_code"]
        condition += "where target_biz_code = '%s'" % target_biz_code
    elif "target_item_code" in kwargs:

        target_item_code = kwargs["target_item_code"]
        condition += "where target_item_code = '%s'" % target_item_code

    sql = "select * from t_das_std_rule_def  " + condition
    try:
        res = execute_query(sql, result_type='dict')
        results = [res[i]['id'] for i in range(len(res))]
        return results
    except Exception as e:
        logging.error("get_std_rule_id：%s" % e)
        return None


def get_std_rule_detail_info(rule_id, args):
    """根据标准化规则id获取规则详情明细

    :param :rule_id 标准化规则id
    :param :args 规则详情明细具体字段

    :return: 返回规则详情明细具体字段value
    """

    sql = "select %s from t_das_std_rule_detail  where rule_id = '%s' order by upt desc" % (args, rule_id)
    try:
        res = execute_query(sql, result_type='dict')
        results = [res[i][args] for i in range(len(res))]
        return results
    except Exception as e:
        logging.error("get_std_rule_detail_id:%s" % e)
        return None